class Print < ActiveRecord::Base
  belongs_to :user
  has_attached_file :attachment,
    :url  => "/uploaded_files/:id/:basename.:extension",
    :path => ":rails_root/uploaded_files/:id/:basename.:extension"

  before_update :set_price
  before_save :set_price
  validates_presence_of :attachment
  validates_presence_of :attachment_file_name
  validates_attachment_content_type :attachment, 
  :content_type =>['image/jpeg' , 'text/plain', 'application/vnd.oasis.opendocument.text', 'image/png', 
    'image/gif' , 'application/zip', 'application/rar', 'application/msword', 
    'application/vnd.openxmlformats-officedocument.wordprocessingml.document', 'application/pdf'], 
    :message => 'nie jest obsługiwany przez nasz system (niedposzuczalny format pliku)'

  validates_numericality_of :pages_bw, :only_integer => true, :greater_than_or_equal_to => 0, :less_than_or_equal_to  => 500
  validates_numericality_of :pages_color, :only_integer => true, :greater_than_or_equal_to => 0, :less_than_or_equal_to  => 500
  validates_numericality_of :copies, :only_integer => true, :greater_than => 0, :less_than_or_equal_to  => 500

def validate
  if self.attachment_file_size > self.user.group.task_quote.megabytes
    errors.add(:attachment, "jest zbyt duży, maksymalny rozmiar to " + self.user.group.task_quote.to_s + " MB")
  end
  if self.printed
    if ((self.pages_bw + self.pages_color) == 0)  # to nie dziala niby
      errors.add(:print,'nie może być pusty! Wprowadź poprawną ilość stron')
    end
  end
end 

  # Zmiana ceny poprzez funkcje
  def self.change_bw_print_price(value)
    const_set(:PRICE_BW, value)
  end

  def self.find_all_printed
    self.find(:all, :conditions => ["printed = ?", true], :order => "created_at desc")
  end
  
  def self.find_all_to_print
    self.find(:all, :conditions => ["printed = ?", false], :order => ":created_at asc")
  end

  # Wartości cenowe należy dopisać do zmiennej globalnej, żeby można było ją łatwo zmieniać.
  def set_price  
    self.price =  self.copies * (self.pages_bw * Settings.first.price_bw + self.pages_color * Settings.first.price_color) * (100 - self.user.group.discount) * 0.01
  end

end
